package com.init.iblog.service.impl;

import com.init.iblog.domain.ResponseResult;
import com.init.iblog.domain.entity.LoginUser;
import com.init.iblog.domain.entity.User;
import com.init.iblog.domain.vo.UserInfoVo;
import com.init.iblog.domain.vo.UserLoginVo;
import com.init.iblog.service.LoginService;
import com.init.iblog.utils.BeanCopyUtils;
import com.init.iblog.utils.JwtUtil;
import com.init.iblog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 前端登录
 */
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * 默认情况下容器中没有，需要自己创建并注入到容器中
     * 通过iblog_front子模块下的config配置中的SecuityConfig配置将其注入到容器中
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 用户退出登录
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取token  解析获取的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("++++++++++++++获取用户认证信息"+authentication.getPrincipal());
        System.out.println(authentication.getPrincipal());
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();

        System.out.println("------------------loginUser的值："+loginUser.toString());
        //获取用户id
        Long id = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject("bloglogin"+id);
        return ResponseResult.okResult();
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public ResponseResult userLogin(User user) {
        //用户认证：传入用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());
        /**
         * authenticationManager最终会调用UserDetailsServiceImpl内的方法，去数据库内进行查询验证用户信息并返回
         */
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        System.out.println(authenticate.getPrincipal());
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //用户id是long类型，将其转化为String类型
        String userId = loginUser.getUser().getId().toString();
        //createJWT(）方法传入一个String后会加密生成一个token
        String jwt = JwtUtil.createJWT(userId);

        //把用户信息存入redis(需要配置redis)
        redisCache.setCacheObject("bloglogin" + userId,loginUser);
        //把token和userinfo封装返回
        //把User转换成UserInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo userLoginVo = new UserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(userLoginVo);
    }
}
